<template>
  <div class="app-container">
    <el-row>
      <el-col>
        <el-select
          v-model="queryParams.year"
          placeholder="选择年份"
          @change="handleYearChange"
        >
          <el-option
            v-for="item in dict.type.biz_work_year_list"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-select
          v-model="queryParams.quarter"
          placeholder="选择季度"
          class="ml-10"
          @change="handleQuarterChange"
        >
          <el-option
            v-for="item in quarterOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-col>
    </el-row>
    <div class="text-banner">
      <span>待审批中心工作（共 {{ centerWorkTotal || 0 }} 条）</span>
      <el-button
        size="mini"
        type="primary"
        circle
        icon="el-icon-refresh"
        plain
        @click="handleRefresh"
      />
    </div>
    <div v-loading="centerWorkLoading">
      <div
        v-for="(centerWork, index) in centerWorkList"
        :key="centerWork.month"
      >
        <div class="month-title">
          <p>
            <span class="month-mark-first">{{ centerWork.quarter }}</span>
            <span>季度中心工作</span>
            <!-- <span class="ml-20">共计</span><span class="month-mark-second">{{ centerWorkMaxScore }}</span> 分， 已分配
            <span class="month-mark-second">{{ centerWork.score }}</span>
            分， 剩余<span class="month-mark-second">{{ centerWorkMaxScore - centerWork.score }}</span
            >分 -->
          </p>
          <div>
            <el-button
              size="mini"
              type="primary"
              plain
              icon="el-icon-menu"
              :disabled="centerWork.disabled"
              @click="handleBatchApproval('pass', centerWork, index)"
            >
              批量通过
            </el-button>
            <el-button
              size="mini"
              type="danger"
              plain
              icon="el-icon-menu"
              :disabled="centerWork.disabled"
              @click="handleBatchApproval('reject', centerWork, index)"
            >
              批量退回
            </el-button>
            <!-- <el-button
              size="mini"
              type="danger"
              plain
              icon="el-icon-edit"
              :disabled="centerWork.disabled"
              @click="handleChangeScore('reject', centerWork, index)"
            >
              修改分值
            </el-button> -->
          </div>
        </div>
        <div>
          <el-table
            :data="centerWork.list"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange($event, index)"
          >
            <el-table-column type="selection" width="45" align="center">
            </el-table-column>
            <el-table-column label="序号" type="index" align="center">
              <template slot-scope="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="normName"
              label="指标名称"
              width="180"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="workContent"
              label="指标打分说明"
              min-width="180"
              align="center"
            >
              <template slot-scope="scope">
                <div class="pre-wrap align-left">
                  {{ scope.row.workContent || "-" }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="deptName"
              label="责任单位"
              width="120"
              align="center"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="planScore"
              label="分值"
              width="120"
              align="center"
            >
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.planScore"
                  placeholder="分值"
                  controls-position="right"
                  :min="0"
                  @change="centerWorkUsedScore(centerWork.quarter)"
                  v-if="scope.row.isScore"
                ></el-input-number>
                <span v-else>{{
                  isNaN(scope.row.planScore) ? "-" : scope.row.planScore
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="workCreateDate"
              label="创建日期"
              width="160"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop=""
              label="纳入进度管理"
              align="center"
              v-if="checkRole(['leadershipGroup', 'performanceOffice'])"
            >
              <template slot-scope="scope">
                <div style="text-align: left" v-hasRole="['performanceOffice']">
                  <el-checkbox
                    :value="Boolean(scope.row.demandCompletionDate)"
                    @change="handelDemandCompletionDateChange(index, scope)"
                    >纳入管理</el-checkbox
                  >
                  <div v-show="Boolean(scope.row.demandCompletionDate)">
                    <span>完成日期：</span>
                    <el-date-picker
                      style="width: 150px; margin-left: 10px"
                      v-model="scope.row.demandCompletionDate"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="要求完成日期"
                      :clearable="false"
                    >
                    </el-date-picker>
                  </div>
                </div>
                <div v-hasRole="['leadershipGroup']">
                  <div v-if="Boolean(scope.row.demandCompletionDate)">
                    <span>完成日期：{{ scope.row.demandCompletionDate }}</span>
                  </div>
                  <div v-else>-</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="操作"
              align="center"
              width="130"
              fixed="right"
            >
              <template slot-scope="scope">
                <div>
                  <el-button
                    type="text"
                    size="mini"
                    v-if="!scope.row.isScore"
                    v-hasPermi="['approval:centerwork:score-change']"
                    @click="handleEditScore(centerWork.quarter, scope.$index)"
                  >
                    调整分值
                  </el-button>
                  <template v-else>
                    <el-button
                      type="text"
                      size="mini"
                      @click="
                        handleSaveEditScore(centerWork.quarter, scope.row)
                      "
                      >保存</el-button
                    >
                    <el-button
                      type="text"
                      size="mini"
                      v-show="scope.row.isScore"
                      @click="getList"
                      >取消</el-button
                    >
                  </template>
                </div>
                <ApprovalLog
                  :biz-id="scope.row.id"
                  v-hasPermi="['approval:centerwork:pass']"
                >
                  <el-button
                    type="text"
                    size="mini"
                    @click.stop="handleApproval(scope.row, 'pass')"
                  >
                    通过
                  </el-button>
                </ApprovalLog>
                <ApprovalLog
                  :biz-id="scope.row.id"
                  v-hasPermi="['approval:centerwork:reject']"
                >
                  <el-button
                    type="text"
                    size="mini"
                    @click.stop="handleApproval(scope.row, 'reject')"
                    class="color-danger ml-10"
                  >
                    退回
                  </el-button>
                </ApprovalLog>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  approval,
  approvalList as listPlan,
  progressManageMarking,
} from "@/api/work-approval";
import { update as updatePlan } from "@/api/work/work-plan";
import { quarterFormat } from "@/utils/quarter.js";
import { getDicts } from "@/api/system/dict/data.js";
import ApprovalLog from "@/components/ApprovalLog";
import dayjs from "dayjs";
import { checkPermi, checkRole } from "@/utils/permission"; // 权限判断函数

export default {
  name: "center-work",
  dicts: ["biz_work_year_list", "biz_work_nature"],
  props: {},
  components: { ApprovalLog },
  data() {
    return {
      centerWorkTotal: 0,
      centerWorkList: [],
      centerWorkMaxScore: 0, // 中心工作最大分值
      centerWorkLoading: false,
      quarterOptions: [],
      queryParams: {
        year: "",
        quarter: "",
        workType: "ZXGZ",
      },
      selectionList: [],
      centerWorkItem: {
        normName: undefined,
        workContent: undefined,
        planScore: 0,
        workCreateDate: undefined,
        workType: "ZXGZ",
        deptName: "",
      },
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getWorkScore();
    this.handleYearChange(new Date().getFullYear());
  },
  methods: {
    checkRole,
    // 纳入进度管理改变
    handelDemandCompletionDateChange(index, raw) {
      if (raw.row.demandCompletionDate) {
        this.$set(
          this.centerWorkList[index]["list"][raw.$index],
          "demandCompletionDate",
          null
        );
      } else {
        this.$set(
          this.centerWorkList[index]["list"][raw.$index],
          "demandCompletionDate",
          dayjs().format("YYYY-MM-DD")
        );
      }
    },
    // 保存修改分值
    handleSaveEditScore(quarter, raw) {
      // 分值验证
      // let findScore = this.centerWorkList.find(item => item.quarter === quarter)['score']
      // if (this.centerWorkMaxScore - findScore < 0) {
      //   this.$message.error(`操作失败，超出剩余可分配分值，请修改！`)
      //   return
      // }
      let mustItem = {};
      let params = {
        year: this.queryParams.year,
        quarter: this.queryParams.quarter,
        id: raw.id,
        workSubmitMark: null,
      };
      for (let key of Object.keys(this.centerWorkItem)) {
        mustItem[key] = raw[key];
      }
      params = { ...params, ...mustItem };
      // 更新
      updatePlan(params).then((res) => {
        this.$modal.msgSuccess("分值已更新");
        this.getList();
      });
    },
    // 修改分值
    handleEditScore(quarter, index) {
      let findindex = this.centerWorkList.findIndex(
        (item) => item.quarter === quarter
      );
      this.$set(this.centerWorkList[findindex].list[index], "isScore", true);
    },
    // 校验表格是否禁选
    checkSelectable(raw, index) {
      if (raw.workAuditStatusDict !== "DSH") {
        return false;
      }
      return true;
    },
    // 表格多选
    handleSelectionChange(selection, index) {
      this.selectionList[index] = selection;
      // 校验批量选择状态
      if (selection.length) {
        this.$set(this.centerWorkList[index], "disabled", false);
      } else {
        this.$set(this.centerWorkList[index], "disabled", true);
      }
    },
    // 批量审批
    handleBatchApproval(operation, raw, index) {
      let auditRemark = "同意";
      let workAuditStatusDict = "SHTG";
      if (operation === "reject") {
        auditRemark = "不同意";
        workAuditStatusDict = "SHBTG";
      }
      let params = this.selectionList[index].map((item) => {
        return {
          id: item.id,
          auditRemark,
          workAuditStatusDict,
          score: item.planScore,
          demandCompletionDate: item.demandCompletionDate,
        };
      });
      let content = `您正在审批 【${raw.quarter}季度】已选中的 ${this.selectionList[index].length} 项工作，请输入审批意见`;
      this.approvalPrompt(operation, content, auditRemark, params);
    },

    // 审批操作
    handleApproval(raw, operation) {
      let params = {
        id: raw.id,
        workAuditStatusDict: "SHTG",
        auditRemark: "同意",
        score: raw.planScore,
        demandCompletionDate: raw.demandCompletionDate,
      };
      if (operation === "reject") {
        params.workAuditStatusDict = "SHBTG";
        params.auditRemark = "不同意";
      }
      let content = `您正在审批 【${raw.quarter}季度-${raw.normName}】 工作项，请输入审批意见`;
      this.approvalPrompt(operation, content, params.auditRemark, [params]);
    },
    // 审批窗口
    approvalPrompt(operation, content, inputValue, params) {
      this.$prompt(content, "审批提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "输入审批意见",
        inputType: "textarea",
        inputPattern: /\S/,
        inputValue: inputValue,
        inputErrorMessage: "审批意见不能为空",
        beforeClose: (action, instance, done) => {
          params.forEach((item) => {
            item.auditRemark = instance.inputValue;
          });
          if (action === "confirm") {
            const loading = this.$loading({
              target: ".el-message-box",
              lock: true,
              text: "数据处理中",
              spinner: "el-icon-loading",
              background: "rgba(255,255,255,0.6)",
            });
            // 纳入进度管理
            let progressList = params
              .filter((ele) => ele.demandCompletionDate) // 过滤掉 demandCompletionDate 为 null 的项
              .map((ele) => ({
                id: ele.id,
                demandCompletionDate: ele.demandCompletionDate,
              }));
            if (progressList.length) {
              progressManageMarking(progressList).catch((err) => {
                this.$modal.msgError("进度管理设置失败");
              });
            }

            approval(params)
              .then(() => {
                loading.close();

                if (operation === "pass") {
                  this.$modal.msgSuccess("已通过");
                } else if (operation === "reject") {
                  this.$modal.msgError("已退回");
                }
                this.handleRefresh();
                done();
              })
              .catch(() => {
                loading.close();
                done();
              });
          } else {
            done();
          }
        },
      });
    },
    // 刷新
    handleRefresh() {
      this.getList();
    },
    // 校验按钮显示
    // 操作类型、审核状态
    checkBtnVisible(type, audit) {
      switch (type) {
        case "pass": // 通过
        case "reject": // 退回
          return audit === "DSH";
        case "finish": // 审核已完成
          return audit === "SHTG";
        default:
          return false;
      }
    },
    // 中心工作已使用分值
    centerWorkUsedScore(quarter) {
      return;
      const index = this.centerWorkList.findIndex(
        (item) => item.quarter == quarter
      );
      const sum = this.centerWorkList[index].list.reduce((prev, curr) => {
        if (curr.planScore) {
          return prev + parseInt(curr.planScore);
        } else {
          return prev;
        }
      }, 0);
      this.$set(this.centerWorkList[index], "score", sum);
    },
    // 获取工作分数限制
    getWorkScore() {
      getDicts("biz_dept_norm_config").then((res) => {
        let { data } = res;
        this.centerWorkMaxScore = data.find(
          (item) => item.dictValue === "ZXGZ"
        )?.remark;
      });
    },
    // 年度选择
    handleYearChange(year) {
      this.queryParams.year = year;
      // 获取当前季度、季度列表（往年默认第一季度）
      let { quarter, quarterList } = quarterFormat(year);
      this.quarterOptions = quarterList;
      this.handleQuarterChange(quarter);
    },
    // 季度选择
    handleQuarterChange(quarter) {
      this.queryParams.quarter = quarter;
      this.getList();
    },
    getList() {
      this.getCenterWorkList();
    },
    // 中心工作列表
    getCenterWorkList() {
      this.centerWorkLoading = true;
      listPlan(this.queryParams)
        .then((res) => {
          let { data } = res;
          this.centerWorkLoading = false;
          this.centerWorkTotal = data.length;
          data.forEach((item) => {
            if (isNaN(item.planScore) || item.planScore === null) {
              item.planScore = 0;
            }
          });
          this.centerWorkList = [
            {
              quarter: this.queryParams.quarter,
              score: 0,
              list: data,
              disabled: true,
            },
          ];
          this.centerWorkUsedScore(this.centerWorkList[0].quarter);
        })
        .catch((err) => (this.centerWorkLoading = false));
    },
  },
};
</script>

<style lang="scss" scoped>
@import url("~@/assets/styles/work.scss");
::v-deep .el-button--text [class*="el-icon-"] + span {
  margin-left: 0;
}

::v-deep .el-input-number--medium {
  width: auto;
}
</style>
